<template>
  <div class="search-view">
    <div class="search-btn">
      <el-button @click="search">拉框查询</el-button>
    </div>
    <div class="search-table" v-show="tableData.length > 0">
      <el-table :data="tableData" @row-click="handleRowClick">
        <el-table-column prop="event_num" label="事件编号" align="center" />
        <el-table-column prop="level" label="事故级别" align="center" />
        <el-table-column prop="area" label="事故区域" align="center" />
        <el-table-column prop="name" label="事故类型" align="center" />
        <el-table-column prop="car_num" label="车牌号" align="center" />
        <el-table-column prop="phone" label="手机号" align="center" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { getWuhanEvents } from '@/api'
import { DrawEvent, DrawRect } from '@antv/l7-draw'
import { ref, inject, onMounted, onBeforeUnmount } from 'vue'
import { PointLayer } from '@antv/l7'
import { pointsWithinPolygon } from '@turf/turf'
const tableData = ref([])
const { map, scene } = inject('mapScene')
let eventData, draw, points, pointLayer
onMounted(async () => {
  map.flyTo({
    center: [114.406325, 30.465113],
    zoom: 15,
    pitch: 45,
  })
  //拿到所有的事故点
  const { data } = await getWuhanEvents()
  eventData = data
})
onBeforeUnmount(() => {
  if (pointLayer) {
    scene.removeLayer(pointLayer)
  }
  if (draw) {
    draw.destroy()
    draw = null
  }
})
function search() {
  if (tableData.value.length > 0) {
    tableData.value = []
  }
  //实现绘图和查询功能
  if (draw) {
    draw.clear()
    draw.destroy()
    draw = null
  }
  if (pointLayer) {
    scene.removeLayer(pointLayer)
    pointLayer = null
  }
  draw = new DrawRect(scene, {})
  draw.enable()
  draw.on(DrawEvent.Add, (e) => {
    //e即使多边形的要素集合
    points = pointsWithinPolygon(eventData, e)
    //1.将点要素数据绘制到地图上
    pointLayer = new PointLayer({ name: 'eventsLayer' })
    pointLayer.source(points).shape('circle').animate(true).active(true).color('pink').size(30)
    scene.addLayer(pointLayer)
    //2.将要素中需要展示的数据放到tableData中 注意需要存入经纬度
    tableData.value = points.features.map((item) => {
      return {
        ...item.properties,
        center: item.geometry.coordinates,
      }
    })
  })
}
function handleRowClick(row) {
  if (draw) {
    draw.destroy()
    draw = null
  }
  const center = row.center
  map.flyTo({
    center,
    zoom: 15,
    pitch: 0,
  })
}
</script>

<style lang="scss" scoped>
.search-view {
  .search-btn {
    position: fixed;
    top: 200px;
    right: 60px;
  }
  .search-table {
    position: fixed;
    width: 60%;
    bottom: 100px;
    left: 20%;
    z-index: 1000;
  }
  .el-table {
    max-height: 300px;
    overflow-y: scroll;
    background-color: #ccc;
  }
  :deep(.el-table__cell) {
    background-color: #ccc;
  }
}
</style>
